<template>
  <div class="common-layout">
    <el-container>
      <el-main style="border-style: groove;border-width: 2px;height: 650px;margin-top: 20px;">
        <div style="margin-bottom: 15px;">
            <el-button color="#626aef" @click="openRole(null,'新增角色')" plain>新增角色</el-button>
            <el-button color="#6d8aa8" @click="openRM" plain>分配菜单</el-button>
        </div>
        <el-table :data="tableData" style="width: 100%">
            <el-table-column fixed type="index" label="编号" width="60" />
            <el-table-column prop="roleName" label="角色名称">
                <template v-slot="scoped">
                    <el-button link @click="openRolename(scoped.row)"  size="small">{{scoped.row.roleName}}</el-button>
                </template>
            </el-table-column>
               <el-table-column prop="createUserName" label="创建人" />
            <el-table-column prop="createTime" label="创建日期" width="200">
                <template v-slot="scoped">
                    <span>{{moment(scoped.row.createTime).format("YYYY-MM-DD HH:mm:ss")}}</span>
                </template>
            </el-table-column>
            <el-table-column prop="updateUserName" label="修改人" />
            <el-table-column prop="updateTime" label="修改日期" width="200">
                 <template v-slot="scoped">
                    <span v-if="scoped.row.updateTime!=null">{{moment(scoped.row.updateTime).format("YYYY-MM-DD HH:mm:ss")}}</span>
                </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" min-width="200">
            <template #default="scoped">
                <el-button link type="primary" size="small" @click="openRole(scoped.row,'修改')">修改</el-button>
                <el-button link type="primary" size="small" @click="remove(scoped.row)">删除</el-button>
                <el-button link type="primary" size="small" @click="assignRole(scoped.row)">分配人员</el-button>
            </template>
            </el-table-column>
        </el-table>
        <div class="demo-pagination-block" style="margin-top: 20px;">
            <el-pagination
            v-model:current-page="page.PageIndex"
            v-model:page-size="page.PageSize"
            :page-sizes="[15, 20, 30, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="page.listcount"
            />
        </div>
      </el-main>
    </el-container>
  </div>

  <!-- 设计角色对话框 -->
<el-dialog v-model="addroleLogic.opens" :title="addroleLogic.title" width="500" draggable align-center>
        <el-form :model="roleData">
        <el-form-item label="角色名称" :label-width="formLabelWidth">
            <el-input v-model="roleData.roleName" autocomplete="off" />
        </el-form-item>
        </el-form>
        <template #footer>
        <div class="dialog-footer">
            <el-button @click="addroleLogic.opens = false">取消</el-button>
            <el-button type="primary" @click="addrole()">
            保存
            </el-button>
        </div>
        </template>
</el-dialog>

<!-- 分配角色对话框 -->
<el-dialog v-model="assignLogic.opens"  width="600" draggable align-center>
    <template #header="{ close, titleId, titleClass }">
      <div class="my-header">
        <h4 :id="titleId" :class="titleClass">请设置【<span style="color: red;">{{ assignLogic.rolename }}</span>】角色的员工</h4>
      </div>
    </template>
    
    <el-form  :inline="true" :model="form">
        
        <el-form-item  :label-width="180" >
            <el-tree
            style="max-width: 600px;"
            :data="data"
            :props="defaultProps"
            default-expand-all
            @node-click="handleNodeClick"
        />
        </el-form-item>
         <el-form-item label="选择员工" :label-width="180" >
             <el-tree
            style="max-width: 600px;"
            :data="userData"
            show-checkbox
            v-model="form.Uid"
            node-key="id"
            ref="treeRef"
            :default-expanded-keys="[2, 3]"
            :props="defaultProps"
            /> 
        </el-form-item>
       
        <el-form-item  :label-width="formLabelWidth" style="float: right;">
            
        </el-form-item>

        
        <!-- <el-form-item label="选择员工" :label-width="formLabelWidth">
              <el-checkbox-group v-model="form.Uid">
                <el-checkbox v-for="a in userData" :label="a.userName" :value="a.id" size="large" />
              </el-checkbox-group>
        </el-form-item> -->
        
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="assignLogic.opens = false">取消</el-button>
        <el-button type="primary" @click="addUserRole()">
          保存
        </el-button>
      </div>
    </template>
</el-dialog>
<!-- 点击角色名称对话框 -->
 <el-dialog v-model="roleLogic.opens"  width="500" draggable align-center>
  <template #header="{ close, titleId, titleClass }">
      <div class="my-header">
        <h4 :id="titleId" :class="titleClass">属于【<span style="color: red;">{{ assignLogic.rolename }}</span>】角色的员工如下</h4>
        <el-button style="margin-left: 50px;" @click="assignRole(roleModel)"><el-icon><Plus /></el-icon></el-button>
      </div>
    </template>
     <div class="flex gap-2">
    <el-tag
      v-for="tag in username"
      :key="tag"
      closable
      style="margin-left: 20px;"
      :disable-transitions="false"
      @close="handleClose(tag)"
    >
      {{ tag.userName }}
    </el-tag>
    <!-- <el-icon><Plus /></el-icon> -->
    </div>
</el-dialog>

<!--角色分配菜单对话框-->

<el-dialog v-model="rmLogic" title="分配菜单" width="500" draggable align-center>
    <el-row>
      <el-col :span="8">
        <div class="grid-content ep-bg-purple" >
          <h3>角色名称</h3>
          <el-tree
            style="max-width: 600px"
            :data="tableData"
            :props="PropsTwo"
            node-key="id"
            ref="RoletreeRef"
            :highlight-current="true"
            @node-click="getRoleMenu()"
          />
           
        </div>
      </el-col>
      <el-col :span="16">
        <div class="grid-content ep-bg-purple-light" >
          <h3>菜单树形</h3>
          <el-tree
            style="max-width: 600px"
            :data="menuData"
            show-checkbox
            node-key="id"
            ref="MenutreeRef"
            default-expand-all
            :props="PropsThree"
          />
        </div>
      </el-col>
    </el-row>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="rmLogic = false">取消</el-button>
        <el-button type="primary" @click="saveRoleMenu()">
          保存
        </el-button>
      </div>
    </template>
</el-dialog>


</template>
<script lang="ts" setup>
import moment from 'moment';
import { onMounted, reactive, ref,watch } from 'vue';
import { readBasic,writeBasic } from '@/Helper/axiosSetting';
import { ElMessage ,ElMessageBox ,type TreeInstance } from 'element-plus';



onMounted(()=>{
    getRoleList()
})
//获取角色列表
const tableData = ref([])
const page=reactive({
    PageIndex:1,
    PageSize:15,
    listcount:0
})
watch(page,()=>{
    getRoleList()
},{deep:true})
const getRoleList=()=>{
    readBasic.get("api/Manage/GetRoleList",{params:{
        PageIndex:page.PageIndex,
        PageSize:page.PageSize
    }}).then(res=>{
        tableData.value=res.data.data.list
        page.listcount=res.data.data.recordCount
    })
}


//新增角色
const formLabelWidth = '140px'
const addroleLogic=reactive({
    opens:false,
    title:''
})
const roleData=reactive({
    "id":0,
    "roleName": "",
    "createTime": "",
    "isDelorUpdate":""
})

const openRole=(row:any,a:string)=>{
    addroleLogic.opens=true;
    addroleLogic.title=a
    if(a=="新增角色"){
        roleData.roleName=""
    }else{
        roleData.id=row.id
        roleData.roleName=row.roleName
        roleData.createTime=row.createTime
        roleData.isDelorUpdate=a
    }

}
//添加+修改
const addrole=()=>{
    if(roleData.roleName==""){
        ElMessage.error('角色名称不能为空');
        return;
    }
    if(addroleLogic.title=="新增角色"){
        writeBasic.post("api/Manage/AddRole",roleData).then(res=>{
        if(res.data.code==200){
            ElMessage.success(res.data.message);
            getRoleList();
            addroleLogic.opens=false;
        }else{
            ElMessage.error(res.data.message)
        }
        })
    } else{
        writeBasic.post("api/Manage/EaditRole",roleData).then(res=>{
        if(res.data.code==200){
            ElMessage.success(res.data.message);
            getRoleList();
            addroleLogic.opens=false;
        }else{
            ElMessage.error(res.data.message)
        }
        })
    }
}
//删除
const remove = (row:any) => {
  ElMessageBox.confirm(
    '确认删除吗?',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      writeBasic.post("api/Manage/EaditRole",row).then(res=>{
        if(res.data.code==200){
            ElMessage.success(res.data.message);
            getRoleList();
            addroleLogic.opens=false;
        }else{
            ElMessage.error(res.data.message)
        }
        })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
} 


interface Tree {
  [key: string]: any
}

const handleNodeClick = (data: Tree) => {
  console.log(data.id)
  getUserData(data.id)
}
//部门信息
const data: Tree[] = [
  {
    label: '选择部门',
    children: [
      {
        id:1,
        label: 'IT信息部',
      },
      {
        id:2,
        label: '人力资源部',
      },
      {
        id:3,
        label: '财务部',
      },
      {
        id:4,
        label: '销售部',
      },
      {
        id:5,
        label: '行政部',
      },
    ],
  },
  
]
const treeRef = ref<TreeInstance>()
const defaultProps = {
  children: 'children',
  label: 'label',
}

//分配角色
const assignLogic=reactive({
    opens:false,
    rolename:'',
})
//获取角色反填数据的实体
const form = reactive({
  departmentId:null,
  Uid:[],
  UidList:"",
  rid:0
})
//打开分配人员对话框
const assignRole=(row:any)=>{
    assignLogic.opens=true;
    assignLogic.rolename=row.roleName
    form.rid=row.id
    // form.departmentId=null
     backName(row.id)
    console.log(row.id)
    console.log(form.UidList)
    
    // form.Uid=form.UidList.split(',').flatMap(Number)
    // form.Uid=[]
    // form.rid=null
}
//获取用户角色
const userData =ref<any>([])
const getUserData=(id:any)=>{
    readBasic.get("api/Manage/GetUserName",{params:{departmentId:id}}).then(res=>{
        userData.value=res.data.data
    })
}

//为角色分配员工
const addUserRole=()=>{
     form.UidList=treeRef.value?.getCheckedKeys(false).toString()||'';
    console.log(form.UidList)
    writeBasic.post("api/Manage/AddUserRole",form).then(res=>{
        if(res.data.data>0){
            ElMessage.success(res.data.message)
            backName(form.rid)
            assignLogic.opens=false
        }else{
            ElMessage.error("分配失败")
        }
    })
}

//分配员工的反填
const backName=(rid:number)=>{
    readBasic.get("api/Manage/GetUserNameDto",{params:{rid:rid}}).then(res=>{
      if(res.data.code==200){
        getUserData(res.data.data.deparmentId)
         treeRef.value?.setCheckedKeys(res.data.data.idList,true);
        form.departmentId=res.data.data.deparmentId
        username.value=res.data.data.userName
      }else{
        getUserData(0)
        treeRef.value?.setCheckedKeys([],true)
        username.value=[]
      }
    })
}



//角色名获取哪些员工
const username=ref<any>([])
const roleLogic=reactive({
  uid:null,
  rid:null,
  opens:false,
})

//角色实体
const roleModel=ref(
   {
        "roleName": "",
        "id": null,
        "createUserName": null,
        "createTime": "",
        "updateUserName": null,
        "updateTime": "",
        "isDelete": false
      }
)

const openRolename=(row:any)=>{
  roleLogic.opens=true
  assignLogic.rolename=row.roleName
  roleLogic.rid=row.id
  backName(row.id)
  roleModel.value=row
}


//❌关闭事件
const handleClose = (tag: any) => {
  username.value.splice(username.value.indexOf(tag), 1)
  console.log(tag)
  roleLogic.uid=tag.id
  writeBasic.post("api/Manage/RemoveUserRole",roleLogic).then(res=>{
    if(res.data.code==200){
      ElMessage.success(res.data.message)
    }else{
      ElMessage.error("删除失败")
    }
  })
}





//----------------------------------角色分配菜单---------------------------------
//分配菜单中间实体
const rmLogic=ref(false)
//打开分配菜单对话框
const openRM=()=>{
  rmLogic.value=true
  getMenuList()
  
}
//角色树形渲染
const PropsTwo = {
  children: 'list',
  label: 'roleName',
}
//实例角色树组件
const RoletreeRef=ref<TreeInstance>()
//实例菜单树组件
const MenutreeRef = ref<TreeInstance>()
//菜单树形渲染
const PropsThree = {
  children: 'children',
  label: 'menuName',
}
//菜单树形实体
const menuData=ref([])
//获取菜单树数据
const getMenuList=()=>{
    readBasic.get("api/Menu/GetMenuList",{params:{
        PageIndex:page.PageIndex,
        PageSize:page.PageSize
    }}).then(res=>{
        menuData.value=res.data.data.list
    })
}
const RMData=reactive({
  rid:0,
  midList:'',
  List:[]
})
//为角色分配菜单
const saveRoleMenu=()=>{

  // RoletreeRef.value?.setCurrentKey(8,false)//反填角色
  console.log(RMData.List.toString())//获取菜单ID数组
  console.log(RoletreeRef.value?.getCurrentNode().id)//获取角色选中节点ID
  RMData.rid=RoletreeRef.value?.getCurrentNode().id
  RMData.midList=MenutreeRef.value?.getCheckedKeys().toString()||""
  console.log(RMData.midList)
  writeBasic.post("api/Menu/RoleMenuAdd",RMData).then(res=>{
    if(res.data.code==200){
      ElMessage.success(res.data.message)
      RMData.List=[]
    }else{
      ElMessage.error("分配失败")
    }
  })


}
//根据角色Id获取拥有的菜单
const getRoleMenu=()=>{
  readBasic.get("api/Menu/GetRoleMenu",{params:{rid:RoletreeRef.value?.getCurrentNode().id}}).then(res=>{
     MenutreeRef.value?.setCheckedKeys(res.data.data,true);
  })
}




</script>

<style scoped>
.my-header {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  gap: 16px;
}


.el-row {
  margin-bottom: 20px;
}

.el-row:last-child {
  margin-bottom: 0;
}

.el-col {
  border-radius: 4px;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
</style>